<template>
  <!-- tablecommon -->
  <div class="commonBoxmp white-bg">
    <div class="HeightAuto">
      <div id="container"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, nextTick } from "vue";
import { useRouter, useRoute } from "vue-router";
import G6 from "@antv/g6";
import { ElMessage, ElMessageBox } from "element-plus";
const router = useRouter();
const route = useRoute();

/*
基本数据类型
引用数据类型（复杂类型） 个人建议 ref初始化变量 
ref 和 reactive 本质我们可以简单的理解为ref是对reactive的二次包装, 
ref定义的数据访问的时候要多一个.value
*/
const state: any = reactive({});
onUnmounted(() => {
  //卸载 清空数据
});
onMounted(() => {
  nextTick(() => {
    setTimeout(() => {
      const HeightAutoDom: any = document.querySelector("#container");
      let height = HeightAutoDom.offsetHeight;
      getInit(height);
    }, 500);
  });
  // setTimeout(() => {
  //   const HeightAutoDom: any = document.querySelector(".containerAntX6");
  //   let height = HeightAutoDom.offsetHeight - 85;
  //   getInit(height);
  // }, 500);
});
/**
 * 撤回
 */
const handleback = () => {
  state.history.undo();
};
/**
 * 向右前进
 */
const handleright = () => {
  state.history.redo();
};
/**
 * 保存数据
 */
const handleSaveData = () => {
  ElMessage.success("保存成功");
  localStorage.setItem("antV", JSON.stringify(state.graph.toJSON()));
};

const getInit = (num: any) => {
  const COLLAPSE_ICON = function COLLAPSE_ICON(x, y, r) {
    return [
      ["M", x - r, y - r],
      ["a", r, r, 0, 1, 0, r * 2, 0],
      ["a", r, r, 0, 1, 0, -r * 2, 0],
      ["M", x + 2 - r, y - r],
      ["L", x + r - 2, y - r],
    ];
  };
  const EXPAND_ICON = function EXPAND_ICON(x, y, r) {
    return [
      ["M", x - r, y - r],
      ["a", r, r, 0, 1, 0, r * 2, 0],
      ["a", r, r, 0, 1, 0, -r * 2, 0],
      ["M", x + 2 - r, y - r],
      ["L", x + r - 2, y - r],
      ["M", x, y - 2 * r + 2],
      ["L", x, y - 2],
    ];
  };

  const data = {
    id: "root",
    label: "",
    title: "发起人",
    error: true,
    nodeType: "a",
    nodeLevel: 2,
    panels: [
      { title: "成功率", value: "11%" },
      { title: "耗时", value: "111" },
      { title: "错误数", value: "111" },
    ],
    children: [
      {
        id: "c1",
        label: "",
        title: "审批人",
        error: true,
        nodeType: "a",
        nodeLevel: 2,
        panels: [
          { title: "成功率", value: "11%" },
          { title: "耗时", value: "111" },
          { title: "错误数", value: "111" },
        ],
        data: {
          approvalType: "发起人自选",
          approvalUser: "大吉大利",
        },
      },
    ],
  };

  G6.Util.traverseTree(data, (d: any) => {
    d.leftIcon = {
      style: {
        fill: "#e6fffb",
        stroke: "#e6fffb",
      },
      img: "https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*Q_FQT6nwEC8AAAAAAAAAAABkARQnAQ",
    };
    return true;
  });

  const ICON_MAP: any = {
    a: "https://gw.alipayobjects.com/mdn/rms_8fd2eb/afts/img/A*0HC-SawWYUoAAAAAAAAAAABkARQnAQ",
    b: "https://gw.alipayobjects.com/mdn/rms_8fd2eb/afts/img/A*sxK0RJ1UhNkAAAAAAAAAAABkARQnAQ",
  };
  G6.registerNode(
    "card-node",
    {
      drawShape: function drawShape(cfg: any, group: any) {
        const color = cfg.error ? "#F4664A" : "#30BF78";
        const r = 2;
        const shape = group.addShape("rect", {
          attrs: {
            x: 0,
            y: 0,
            width: 200,
            height: 60,
            stroke: color,
            radius: r,
          },
          name: "main-box",
          draggable: true,
        });

        group.addShape("rect", {
          attrs: {
            x: 0,
            y: 0,
            width: 200,
            height: 20,
            fill: color,
            radius: [r, r, 0, 0],
          },
          name: "title-box",
          draggable: true,
        });

        // left icon
        group.addShape("image", {
          attrs: {
            x: 4,
            y: 2,
            height: 16,
            width: 16,
            cursor: "pointer",
            img: ICON_MAP[cfg.nodeType || "app"],
          },
          name: "node-icon",
        });

        // title text
        group.addShape("text", {
          attrs: {
            textBaseline: "top",
            y: 2,
            x: 24,
            lineHeight: 20,
            text: cfg.title,
            fill: "#fff",
          },
          name: "title",
        });

        if (cfg.nodeLevel > 0) {
          group.addShape("marker", {
            attrs: {
              x: 184,
              y: 10,
              r: 6,
              cursor: "pointer",
              symbol: cfg.collapse ? G6.Marker.expand : G6.Marker.collapse,
              stroke: "#666",
              lineWidth: 1,
            },
            name: "collapse-icon",
          });
        }

        // The content list
        cfg.panels.forEach((item: any, index: any) => {
          // name text
          group.addShape("text", {
            attrs: {
              textBaseline: "top",
              y: 25,
              x: 24 + index * 60,
              lineHeight: 20,
              text: item.title,
              fill: "rgba(0,0,0, 0.4)",
            },
            name: `index-title-${index}`,
          });

          // value text
          group.addShape("text", {
            attrs: {
              textBaseline: "top",
              y: 42,
              x: 24 + index * 60,
              lineHeight: 20,
              text: item.value,
              fill: "#595959",
            },
            name: `index-title-${index}`,
          });
        });
        return shape;
      },
    },
    "single-node",
  );
  G6.registerEdge("flow-line", {
    draw(cfg, group) {
      const startPoint: any = cfg.startPoint;
      const endPoint: any = cfg.endPoint;

      const { style }: any = cfg;
      const shape = group.addShape("path", {
        attrs: {
          stroke: style.stroke,
          endArrow: style.endArrow,
          path: [
            ["M", startPoint.x, startPoint.y],
            ["L", startPoint.x, (startPoint.y + endPoint.y) / 2],
            ["L", endPoint.x, (startPoint.y + endPoint.y) / 2],
            ["L", endPoint.x, endPoint.y],
          ],
        },
      });

      return shape;
    },
  });

  const defaultStateStyles = {
    hover: {
      stroke: "#1890ff",
      lineWidth: 2,
    },
  };

  const defaultNodeStyle = {
    fill: "#fff",
    stroke: "#40a9ff",
    radius: 5,
  };

  const defaultEdgeStyle = {
    stroke: "#91d5ff",
    endArrow: {
      path: "M 0,0 L 12, 6 L 9,0 L 12, -6 Z",
      fill: "#91d5ff",
      d: -20,
    },
  };

  const defaultLayout = {
    type: "compactBox",
    direction: "TB",
    getId: function getId(d: any) {
      return d.id;
    },
    getHeight: function getHeight() {
      return 16;
    },
    getWidth: function getWidth() {
      return 16;
    },
    getVGap: function getVGap() {
      return 40;
    },
    getHGap: function getHGap() {
      return 170;
    },
  };

  const defaultLabelCfg = {
    style: {
      fill: "#000",
      fontSize: 12,
    },
  };

  const container: any = document.getElementById("container");
  const width = container.scrollWidth;
  // const minimap = new G6.Minimap({
  //   size: [150, 100],
  //   type:"keyShape",
  // });
  const graph = new G6.TreeGraph({
    fitCenter: true,
    maxZoom: 1.3,
    container: "container",
    width,
    height: num,

    linkCenter: true,
    plugins: [],
    modes: {
      default: ["drag-canvas", "zoom-canvas"],
    },
    defaultNode: {
      type: "card-node",
    },
    defaultEdge: {
      type: "flow-line",
      style: defaultEdgeStyle,
    },
    // nodeStateStyles: defaultStateStyles,
    // edgeStateStyles: defaultStateStyles,
    layout: defaultLayout,
  });
  graph.data(data);
  graph.render();
  graph.fitView();

  graph.on("node:mouseenter", (evt) => {
    const { item }: any = evt;
    console.log("item :>> ", item);
    graph.setItemState(item, "hover", true);
  });

  graph.on("node:mouseleave", (evt) => {
    const { item }: any = evt;
    graph.setItemState(item, "hover", false);
  });

  graph.on("node:click", (evt) => {
    const { item, target }: any = evt;
    const targetType = target.get("type");
    const name = target.get("name");

    // 增加元素
    if (targetType === "marker") {
      const model: any = item.getModel();
      if (name === "collapse-icon") {
        if (!model.children) {
          model.children = [];
        }
        const id = `n-${Math.random()}`;
        model.children.push({
          id,
          label: "",
          title: "审批人",
          error: true,
          nodeType: "a",
          nodeLevel: 2,
          panels: [
            { title: "成功率", value: "11%" },
            { title: "耗时", value: "111" },
            { title: "错误数", value: "111" },
          ],
          data: {
            approvalType: "发起人自选",
            approvalUser: "大吉大利",
          },
        });
        graph.updateChild(model, model.id);
      } else if (name === "remove-item") {
        graph.removeChild(model.id);
      }
    }
  });

  if (typeof window !== "undefined")
    window.onresize = () => {
      if (!graph || graph.get("destroyed")) return;
      if (!container || !container.scrollWidth || !container.scrollHeight)
        return;
      graph.changeSize(container.scrollWidth, container.scrollHeight);
    };
};
/**
 * 删除选中
 */
const handleDeleteCell = () => {
  let data = state.graph.getSelectedCells();
  state.graph.model.removeCells(data);
};
</script>

<style scoped lang="scss">
#container {
  width: 100%;
  height: 100%;
}
</style>
